<template>
  <div class="page-wapper">
    <!-- <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 我的日报
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div> -->

    <!-- 左侧顶部年份显示 -->
    <div class="year_box">
      <div class="year_icon">{{ dateProgressYear }}</div>
    </div>

    <!-- 左侧垂直计数栏 -->
    <DateProgress
      ref="dateProgressRef"
      :height="dateProgressHeight"
      :year="dateProgressYear"
      @changeWeek="changeWeekMethod"
      @changeYear="changeYearMethod"
    />

    <!-- 右上角周报按钮 -->
    <div class="week_report_btn">
      <el-tooltip content="周报" placement="top">
        <Calendar
          class="week_report_icon without-outline"
          @click="openWeekReportDialog"
        />
      </el-tooltip>
      <div
        v-if="weekReportList.length"
        class="selected_report_count"
        :class="{ active: isSelectCountShowAni }"
      >
        {{ weekReportList.length }}
      </div>
    </div>

    <div class="container pl_l" ref="containerRef">
      <!-- 顶部星期导航栏 -->
      <ColorTabs
        ref="colorTabsRef"
        @onTab="onTabMethod"
        @goWeek="goWeekMethod"
      />

      <!-- 按钮栏 -->

      <div class="control_bar">
        <TableButtonGroup
          v-if="isPhone"
          :buttonList="getButtonList()"
          :showCount="2"
        />
        <template v-else>
          <div>
            <el-button size="mini" type="warning" @click="copyMethod">
              复制
            </el-button>
            <el-button size="mini" type="primary" @click="addWeekReport">
              添加周报
            </el-button>
            <el-button
              size="mini"
              type="primary"
              @click="addWeekReportAll"
              :loading="addWeekReportAllBtnLoading"
            >
              一键添加周报
            </el-button>
            <el-button
              v-if="isShowSendReportBtn"
              size="mini"
              type="danger"
              @click="handleSendTodayReport"
              :loading="sendTodayReportBtnLoading"
            >
              发送日报
            </el-button>
            <el-button
              v-else
              size="mini"
              type="primary"
              @click="viewSendedReport"
            >
              查看已发送日报
            </el-button>
          </div>
          <div>
            <el-button size="mini" type="primary" @click="createTableData">
              新建
            </el-button>
            <el-button size="mini" type="danger" @click="deleteAll">
              删除
            </el-button>
          </div>
        </template>
      </div>

      <!-- 表格 -->
      <div class="table_box f_1">
        <!--
          show-overflow="tooltip"
        -->
        <vxe-table
          v-loading="tableLoading"
          :data="tableData"
          :sort-config="{ remote: true }"
          :menu-config="{}"
          :checkbox-config="{ checkField: 'checked', trigger: 'row' }"
          :row-style="rowStyle"
          :scroll-y="{ enabled: false }"
          ref="xTable"
          resizable
          align="center"
          border
          height="100%"
          highlight-hover-row
          highlight-current-row
          @cell-menu="cellContextMenuEvent"
          @checkbox-all="selectAllChangeEvent"
          @checkbox-change="selectChangeEvent"
          class="xTable"
        >
          <vxe-column
            type="checkbox"
            width="60"
            :fixed="isPhone ? null : 'left'"
          ></vxe-column>

          <vxe-column
            type="seq"
            title="序号"
            width="60"
            :fixed="isPhone ? null : 'left'"
          ></vxe-column>

          <vxe-column
            title="模块名称"
            min-width="220"
            align="left"
            header-align="center"
          >
            <template #default="{ row }">
              <span v-for="(cell, j) in row.moduleNamesArr" :key="j">
                【{{ cell }}】
              </span>
            </template>
          </vxe-column>

          <vxe-column
            field="reportText"
            title="工作内容"
            min-width="300"
            align="left"
            header-align="center"
          ></vxe-column>

          <vxe-column title="工作进度" width="100">
            <template #default="{ row }">
              <div v-if="Number(row.workProgress)">
                {{ row.workProgress }} %
              </div>
            </template>
          </vxe-column>

          <vxe-column
            field="reportTime"
            title="报告时间"
            width="120"
          ></vxe-column>

          <!-- <vxe-column
            field="reportName"
            title="报告人"
            width="100"
          ></vxe-column> -->

          <vxe-column
            #default="{ row }"
            width="160"
            title="操作"
            :fixed="isPhone ? null : 'right'"
          >
            <div>
              <!-- <el-button size="mini" type="text"  @click="copyContentMethod(row)">复制内容</el-button> -->
              <el-button
                size="mini"
                type="text"
                @click.stop="editTableDataMethod(row)"
              >
                编辑
              </el-button>
              <!-- style="color: #f56c6c" -->
              <el-button
                size="mini"
                type="text"
                @click.stop="deleteTableDataMethod(row)"
              >
                删除
              </el-button>
            </div>
          </vxe-column>
        </vxe-table>
      </div>

      <!-- 周报弹框 -->
      <div
        v-if="weekReportDialogVisible"
        class="week_dialog_mask"
        @click="closeWeekReportDialog"
      >
        <div
          v-loading="weekReportDialogLoading"
          :class="{ show: dialogShow }"
          class="week_dialog p_m"
          @click.stop=""
        >
          <div class="show_box mb_m">
            <div v-if="weekReportDateList.length">
              <div
                class="week_item mb_m"
                v-for="(obj, k) in weekReportDateList"
                :key="k"
              >
                <div class="week_date_title pb_s d_f j_s a_c">
                  <span class="week">{{ obj.week }}</span>
                  <span class="date">{{ obj.date }}</span>
                </div>
                <ul>
                  <li v-for="(item, i) in obj.list" :key="i" class="list_item">
                    <div class="item_content">
                      <span class="seq">{{ i + 1 }}</span>
                      <span class="split_char">{{ item.splitChar }}</span>
                      <span v-for="(cell, j) in item.moduleNamesArr" :key="j"
                        >【{{ cell }}】</span
                      >
                      <span>{{ item.reportText }}&nbsp;&nbsp;</span>
                    </div>

                    <div
                      class="delete_btn"
                      @click="deleteWeekReportMethod(item, i)"
                    >
                      <delete-filled
                        style="
                          width: 1.2em;
                          height: 1.2em;
                          margin-right: 14px;
                          color: #f56c6c;
                        "
                      />
                    </div>
                  </li>
                </ul>
              </div>
              <!-- 下周工作计划 -->
              <div class="next_week_plan_box">
                <div
                  v-for="(item, i) in nextWeekPlanList"
                  :key="i"
                  class="next_week_plan_item"
                >
                  <el-input
                    v-model="item.projectName"
                    size="small"
                    placeholder="下周工作项目"
                    clearable
                    style="width: 35%; margin-right: 10px"
                  ></el-input>
                  <el-input
                    v-model="item.planTarget"
                    size="small"
                    placeholder="计划达成目标"
                    clearable
                  ></el-input>
                  <CirclePlus
                    v-if="i === 0"
                    class="icon add"
                    @click="addNextWeekPlanItem"
                  />
                  <Delete
                    v-else
                    class="icon delete"
                    @click="deleteNextWeekPlanItem(i)"
                  />
                </div>
              </div>
            </div>
            <div v-else>
              <el-empty description="您还未添加周报"></el-empty>
            </div>
          </div>
          <div class="align_center">
            <el-button
              type="primary"
              size="mini"
              @click.stop="confirmExportWeekReport"
            >
              导出周报
            </el-button>
            <el-button type="warning" size="mini" @click.stop="clearWeekReport">
              清空
            </el-button>
            <el-button
              type="info"
              size="mini"
              @click.stop="closeWeekReportDialog"
            >
              取消
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <ReportFormDialog ref="reportFormDialogRef" @refresh="refreshList" />

    <!-- 鼠标右键菜单 -->
    <context-menu name="context-menu-1">
      <!--
                @click.prevent="copySelection"
                待处理的问题：
                    使用了这个插件之后，拿不到鼠标的选中文字，做不了复制选中，
                    但是使用按钮却可以拿到，说明是组件的问题，可能需要自己写一个！
             -->
      <context-menu-item
        :divider="true"
        @itemClickHandle="
          (ctx) => {
            itemClickEvent(ctx, '复制内容');
          }
        "
      >
        <document-copy class="icon" />复制内容
      </context-menu-item>
      <context-menu-item
        @itemClickHandle="
          (ctx) => {
            itemClickEvent(ctx, '复制整条');
          }
        "
      >
        <document-copy class="icon" />复制整条
      </context-menu-item>
      <context-menu-item
        :divider="true"
        @itemClickHandle="
          (ctx) => {
            itemClickEvent(ctx, '编辑');
          }
        "
      >
        <Edit class="icon" />编辑
      </context-menu-item>
      <context-menu-item
        @itemClickHandle="
          (ctx) => {
            itemClickEvent(ctx, '删除');
          }
        "
      >
        <Delete class="icon" />删除
      </context-menu-item>
    </context-menu>

    <!-- 发送日报弹框 -->
    <ReportCommitDialog
      ref="reportCommitDialogRef"
      @refresh="getCommitCountSelf"
    />
  </div>
</template>

<script>
import {
  ref,
  reactive,
  getCurrentInstance,
  onMounted,
  inject,
  nextTick,
  computed,
  onActivated,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
// import { getSelections } from "../../utils/common";
import ColorTabs from "../../components/ColorTabs.vue";
import DateProgress from "../../components/DateProgress.vue";
import ReportFormDialog from "./components/ReportFormDialog.vue";
import ReportCommitDialog from "./components/ReportCommitDialog.vue";
import TableButtonGroup from "../../components/tableButtonGroup.vue";
import _ from "lodash";
import { copyInClip } from "../../utils/common";

export default {
  name: "reportTable",
  components: {
    ColorTabs,
    DateProgress,
    ReportFormDialog,
    ReportCommitDialog,
    TableButtonGroup,
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const emitContext = inject("emitContext");
    const showPageAlert = inject("showPageAlert");
    const $api = proxy.$api;
    const $moment = proxy.$moment;
    const store = useStore();
    const router = useRouter();
    const userInfo = computed(() => store.state.user.userInfo);
    const isPhone = computed(() => store.state.isPhone);

    const query = reactive({
      address: "",
      name: "",
      pageIndex: 1,
      pageSize: 10,
    });
    const tableData = ref([]);
    const pageTotal = ref(0);
    const tableLoading = ref(false);
    const containerRef = ref(null);
    // 缓存当前选中的日期
    let currentDateStr = "";

    // 刷新列表
    const refreshList = () => {
      getData(currentDateStr);
    };

    // -------------- 发送日报弹框 start ---------------------------
    const reportCommitDialogRef = ref(null);
    const sendTodayReportBtnLoading = ref(false);
    const isShowSendReportBtn = ref(false);

    // 打开弹框
    const openReportCommitDialog = (list) => {
      nextTick(() => {
        reportCommitDialogRef.value.open(list);
      });
    };

    // 关闭弹框
    const closeReportCommitDialog = () => {
      nextTick(() => {
        reportCommitDialogRef.value.close();
      });
    };

    // 发送日报
    const handleSendTodayReport = () => {
      // const selectedList = tableData.value.filter((item) => item.checked);
      // if (!selectedList.length) {
      //   return ElMessage.warning("请选择列表的数据");
      // }
      // openReportCommitDialog(selectedList);
      const startDateTime = $moment()
        .startOf("day")
        .format("YYYY-MM-DD HH:mm:ss");
      const endDateTime = $moment().endOf("day").format("YYYY-MM-DD HH:mm:ss");
      sendTodayReportBtnLoading.value = true;
      $api.report
        .getToDayReportList({
          current: 1,
          size: 999,
          startDateTime,
          endDateTime,
        })
        .then((res) => {
          sendTodayReportBtnLoading.value = false;
          const todayPlanReportList = res.data.list.map((item) => {
            return {
              ...item,
              checked: false,
              moduleNamesArr: item.moduleNames
                .split("|")
                .filter((item) => item),
              moduleIdsArr: item.moduleIds.split("|").filter((item) => item),
            };
          });
          if (todayPlanReportList.length) {
            router.push({
              name: "reportCommitForm",
              params: {
                refresh: true,
              },
            });
            // openReportCommitDialog(todayPlanReportList);
          } else {
            ElMessage.warning("请先添加今天的工作计划");
          }
        })
        .catch((err) => {
          sendTodayReportBtnLoading.value = false;
          console.error("handleSendTodayReport error: ", err);
        });
    };

    // 查询当前登录用户的今日日报提交记录数量
    const getCommitCountSelf = () => {
      $api.reportCommit
        .getCommitCountSelf()
        .then((res) => {
          isShowSendReportBtn.value = res.data === 0;
          if (isShowSendReportBtn.value) {
            showPageAlert({
              message: "亲，您今天还没有发送日报哦~",
              key: "getCommitCountSelf",
              type: "warning",
            });
          }
        })
        .catch((err) => {
          console.error("getCommitCountSelf error: ", err);
        });
    };

    // 查看已发送日报
    const viewSendedReport = () => {
      router.push({
        name: "SendedReportManage",
      });
    };

    // -------------- 发送日报弹框 end ---------------------------

    // 获取表格数据
    const getData = (dateStr) => {
      if (!dateStr) {
        return console.error("getData error: dateStr is null !");
      }
      currentDateStr = dateStr;
      const startDateTime = dateStr + " 00:00:00";
      const endDateTime = dateStr + " 23:59:59";
      tableLoading.value = true;
      $api.report
        .getToDayReportList({
          current: 1,
          size: 999,
          startDateTime,
          endDateTime,
        })
        .then((res) => {
          tableLoading.value = false;
          tableData.value = res.data.list.map((item) => {
            return {
              ...item,
              checked: false,
              moduleNamesArr: item.moduleNames
                .split("|")
                .filter((item) => item),
              moduleIdsArr: item.moduleIds.split("|").filter((item) => item),
            };
          });
        })
        .catch((err) => {
          tableLoading.value = false;
          console.error("tableData error: ", err);
        });
    };

    // 单元行选择事件
    const selectChangeEvent = ({ checked, records }) => {
      console.log("selectChangeEvent ==> checked", checked);
      console.log("selectChangeEvent ==> records", records);
    };

    // 单元行全选事件
    const selectAllChangeEvent = ({ checked, records }) => {
      console.log("selectAllChangeEvent ==> checked", checked);
      console.log("selectAllChangeEvent ==> records", records);
    };

    // 动态设置单元行样式
    const rowStyle = ({ rowIndex }) => {
      if (tableData.value[rowIndex].checked) {
        return {
          backgroundColor: "pink",
          // backgroundColor: 'lightblue',
          // color: '#ffffff'
        };
      }
    };

    // 点击tab标签
    const onTabMethod = (dateStr) => {
      if (dateStr) {
        getData(dateStr);
      } else {
        tableData.value = [];
      }
    };

    const dateProgressRef = ref(null);
    // 调用 progress 组件日期前进后退方法
    const goWeekMethod = (type) => {
      dateProgressRef.value.goWeekCountMethod(type);
    };

    const colorTabsRef = ref(null);

    // 给日期 tab 重新设定date
    const changeWeekMethod = (firstDateInWeek) => {
      nextTick(() => {
        colorTabsRef.value.setWeekDateListMethod(firstDateInWeek);
      });
    };

    const changeYearMethod = (type) => {
      if (type === 1) {
        dateProgressYear.value++;
      } else if (type === -1) {
        dateProgressYear.value--;
      }
    };

    // 复制内容
    const copyContentMethod = (row) => {
      console.log("复制内容 =>");
    };

    // 删除内容接口
    const deleteTableData = (ids) => {
      tableLoading.value = true;
      $api.report
        .deleteReport({
          ids,
        })
        .then((res) => {
          ElMessage.success("删除成功！");
          refreshList();
        })
        .catch((err) => {
          console.error("deleteReport error: ", err);
        })
        .finally(() => {
          tableLoading.value = false;
        });
    };

    // 删除单个内容
    const deleteTableDataMethod = (row) => {
      // 二次确认删除
      ElMessageBox.confirm(
        `确定要删除【${
          row.reportText.length > 10
            ? row.reportText.slice(0, 10) + "..."
            : row.reportText
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          deleteTableData([row.id]);
        })
        .catch(() => {});
    };

    // 复制功能
    const copyMethod = () => {
      const selectedList = tableData.value.filter((item) => item.checked);
      if (!selectedList.length) {
        return ElMessage.warning("请选择列表的数据");
      }
      let content = "";
      // 获取当前选择的日期
      content += colorTabsRef.value.getActiveTabDate() + "\n";
      selectedList.forEach((item, index) => {
        content += index + 1;
        content += item.splitChar;
        item.moduleNamesArr.forEach((cell, j) => {
          content += `【${cell}】`;
        });
        content += item.reportText + "  ";
        if (Number(item.workProgress)) {
          content += `${item.workProgress}%  `;
        }
        // content += `(${item.reportName})`;
        content += "\n";
      });
      // console.log('content = ' + content)
      copyInClip(content);
    };

    const reportFormDialogRef = ref(null);

    // 编辑内容
    const editTableDataMethod = (row) => {
      // console.log('编辑内容 => form', form)
      nextTick(() => {
        reportFormDialogRef.value.open(row);
      });
    };

    // 新建
    const createTableData = () => {
      // 需要检查有没有填写真实姓名
      if (!userInfo.value.truename) {
        ElMessageBox.confirm(
          `你还没有填写你的【姓名】，需要现在去填写吗？`,
          "提示",
          { type: "warning" }
        )
          .then(() => {
            router.push({
              name: "user",
              params: {
                truename: true,
              },
            });
          })
          .catch(() => {});
        return;
      }
      nextTick(() => {
        const reportTime = colorTabsRef.value.getActiveTabDate();
        reportFormDialogRef.value.open(null, reportTime);
      });
    };

    // 鼠标右键菜单
    const cellContextMenuEvent = ({ column, $event, row }) => {
      emitContext($event, { name: "context-menu-1", row });
    };

    // 删除全部
    const deleteAll = () => {
      if (!tableData.value.length) {
        return ElMessage.warning("没啥可删的");
      }
      const selectedList = tableData.value.filter((item) => item.checked);
      if (!selectedList.length) {
        return ElMessage.warning("请选择列表的数据");
      }
      // 二次确认删除
      ElMessageBox.confirm(
        `确定要删除 ${selectedList.length} 条数据吗？`,
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          const ids = selectedList.map((item) => item.id);
          deleteTableData(ids);
        })
        .catch(() => {});
    };

    const itemClickEvent = (ctx, key) => {
      const item = ctx.row;
      let content = "";
      switch (key) {
        case "编辑":
          editTableDataMethod(item);
          break;
        case "复制整条":
          item.moduleNamesArr.forEach((cell, j) => {
            content += `【${cell}】`;
          });
          content += item.reportText + "  ";
          content += `${item.workProgress}%  `;
          content += `(${item.reportName})`;
          content += "\n";
          copyInClip(content);
          break;
        case "复制内容":
          content = item.reportText;
          copyInClip(content);
          break;
        case "删除":
          deleteTableDataMethod(item);
          break;
        case "复制所选":
          // content = '复制所选'
          // copyInClip(content)

          console.log(window.getSelection().toString());

          break;
      }
    };

    const copySelection = () => {
      // console.log("copySelection => ", getSelections()); // 未能拿到鼠标选择的文字？？？
    };

    /** ------------------------- 周报弹框部分 start ------------------------ */
    const weekReportDialogVisible = ref(false);
    // 控制dialog样式
    const dialogShow = ref(false);
    const weekReportDialogLoading = ref(false);
    const addWeekReportAllBtnLoading = ref(false);
    const isSelectCountShowAni = ref(false);
    const nextWeekPlanList = ref([
      {
        projectName: "",
        planTarget: "",
      },
    ]);

    const createEmptyNextWeekPlanItem = () => {
      return {
        projectName: "",
        planTarget: "",
      };
    };

    // 周报列表
    const weekReportList = ref([]);

    const addNextWeekPlanItem = () => {
      const item = createEmptyNextWeekPlanItem();
      nextWeekPlanList.value.push(item);
    };

    const deleteNextWeekPlanItem = (index) => {
      if (nextWeekPlanList.value.length > 1) {
        nextWeekPlanList.value.splice(index, 1);
      }
    };

    // 页面显示的周报列表
    const weekReportDateList = computed(() => {
      const list = [];
      if (weekReportList.value.length) {
        const sortArr = _.cloneDeep(weekReportList.value).sort((a, b) => {
          const am = new Date(a.reportTime).getTime();
          const bm = new Date(b.reportTime).getTime();
          return am - bm;
        });
        sortArr.forEach((item) => {
          const index1 = list.findIndex(
            (cell) => cell.date === item.reportTime
          );
          if (index1 === -1) {
            const weekObj = {
              date: item.reportTime,
              week: computeWeek(item.reportTime),
              list: [],
            };
            weekObj.list.push(item);
            list.push(weekObj);
          } else {
            list[index1].list.push(item);
          }
        });
      }
      return list;
    });

    const computeWeek = (date) => {
      const time = new Date(date);
      let week = "";
      switch (time.getDay()) {
        case 0:
          week = "星期日";
          break;
        case 1:
          week = "星期一";
          break;
        case 2:
          week = "星期二";
          break;
        case 3:
          week = "星期三";
          break;
        case 4:
          week = "星期四";
          break;
        case 5:
          week = "星期五";
          break;
        case 6:
          week = "星期六";
          break;
      }
      return week;
    };

    // 打开周报弹框
    const openWeekReportDialog = () => {
      if (weekReportDialogVisible.value) {
        return;
      }
      weekReportDialogVisible.value = true;
      setTimeout(() => {
        dialogShow.value = true;
      }, 50);
    };

    // 关闭周报弹框
    const closeWeekReportDialog = () => {
      dialogShow.value = false;
      setTimeout(() => {
        weekReportDialogVisible.value = false;
      }, 300);
    };

    // 清空周报
    const clearWeekReport = () => {
      if (!weekReportList.value.length) {
        return closeWeekReportDialog();
      }
      // 二次确认
      ElMessageBox.confirm(`确定要清空所有吗？`, "提示", { type: "warning" })
        .then(() => {
          weekReportList.value = [];
          nextWeekPlanList.value = [
            {
              projectName: "",
              planTarget: "",
            },
          ];
          closeWeekReportDialog();
        })
        .catch(() => {});
    };

    // 添加周报
    const addWeekReport = () => {
      const selectedList = tableData.value.filter((item) => item.checked);
      if (!selectedList.length) {
        return ElMessage.warning("请先选择要添加的数据");
      }
      let count = 0;
      selectedList.forEach((item) => {
        const indexFind = weekReportList.value.findIndex(
          (cell) => cell.id === item.id
        );
        if (indexFind === -1) {
          weekReportList.value.push(item);
          count++;
        }
      });
      if (count > 0) {
        showSelectCountAni();
        ElMessage.success(`添加了${count}条新内容`);
      } else {
        ElMessage.success(`所选内容均已添加`);
      }
    };

    // 一键添加7天的周报
    const addWeekReportAll = () => {
      nextTick(() => {
        const dateList = colorTabsRef.value.dateList;
        const startDateTime = dateList[0].date + " 00:00:00";
        const endDateTime = dateList[dateList.length - 1].date + " 23:59:59";
        addWeekReportAllBtnLoading.value = true;
        $api.report
          .getToDayReportList({
            current: 1,
            size: 999,
            startDateTime,
            endDateTime,
          })
          .then((res) => {
            ElMessage.success("添加成功！");
            weekReportList.value = res.data.list.map((item) => {
              return {
                ...item,
                checked: false,
                moduleNamesArr: item.moduleNames
                  .split("|")
                  .filter((item) => item),
                moduleIdsArr: item.moduleIds.split("|").filter((item) => item),
              };
            });
          })
          .catch((err) => {
            console.error("addWeekReportAll error: ", err);
          })
          .finally(() => {
            addWeekReportAllBtnLoading.value = false;
          });
      });
    };

    // 删除周报
    const deleteWeekReportMethod = (item, i) => {
      // 二次确认
      // ElMessageBox.confirm(
      //   `确定要删除【${
      //     item.reportText.length > 10
      //       ? item.reportText.slice(0, 10) + "..."
      //       : item.reportText
      //   }】吗？`,
      //   "提示",
      //   { type: "warning" }
      // )
      //   .then(() => {
      //     const index = weekReportList.value.findIndex(
      //       (cell) => cell.id === item.id
      //     );
      //     weekReportList.value.splice(index, 1);
      //     ElMessage.success("删除成功");
      //   })
      //   .catch(() => {});

      const index = weekReportList.value.findIndex(
        (cell) => cell.id === item.id
      );
      weekReportList.value.splice(index, 1);
      ElMessage.success("删除成功");
    };

    // 导出周报
    const confirmExportWeekReport = () => {
      if (!weekReportList.value.length) {
        return ElMessage.warning("请先添加周报");
      }
      // 二次确认
      ElMessageBox.confirm(`确定要全部导出吗？`, "提示", {
        type: "warning",
      })
        .then(() => {
          exportWeekReport();
        })
        .catch(() => {});
    };

    // 导出周报接口
    const exportWeekReport = () => {
      weekReportDialogLoading.value = true;
      const reportIds = weekReportList.value.map((item) => item.id);
      const nextWeekPlanFilterList = nextWeekPlanList.value.filter(
        (item) => item.projectName || item.planTarget
      );
      $api.report
        .exportWeekReport({
          reportIds,
          nextWeekPlanList: nextWeekPlanFilterList,
        })
        .then((res) => {
          weekReportDialogLoading.value = false;
          const exportDate =
            weekReportDateList.value[weekReportDateList.value.length - 1].date;
          exportResponse(
            res,
            `${exportDate}周报-${userInfo.value.truename}.xlsx`
          );
        })
        .catch((err) => {
          weekReportDialogLoading.value = false;
          console.error("exportWeekReport error: ", err);
        });
    };

    // 导出响应
    const exportResponse = (res, fileName) => {
      const content = res;
      const blob = new Blob([content], {
        type: "application/vnd.ms-excel;charset=utf-8",
        // type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
      });
      const elink = document.createElement("a");
      // 非IE下载
      if ("download" in elink) {
        elink.download = fileName; // 文件名字
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();

        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      }
      // IE10+下载
      else {
        navigator.msSaveBlob(blob, fileName);
      }
    };

    const showSelectCountAni = () => {
      if (isSelectCountShowAni.value) return;
      isSelectCountShowAni.value = true;
      setTimeout(() => {
        isSelectCountShowAni.value = false;
      }, 300);
    };
    /** ------------------------- 周报弹框部分 end ------------------------ */

    const getButtonList = () => {
      return [
        {
          text: "复制",
          onClick: copyMethod,
        },
        {
          text: "新建",
          onClick: createTableData,
        },
        {
          text: "删除",
          onClick: deleteAll,
        },
        {
          text: "添加周报",
          onClick: addWeekReport,
        },
        {
          text: "一键添加周报",
          onClick: addWeekReportAll,
        },
        {
          text: "发送日报",
          onClick: handleSendTodayReport,
        },
        {
          text: "查看已发送日报",
          onClick: viewSendedReport,
        },
      ];
    };

    // 初始化
    const dateProgressHeight = ref(547);
    const dateProgressYear = ref(0);
    dateProgressYear.value = $moment().weekYear();

    onMounted(() => {
      dateProgressHeight.value = containerRef.value.offsetHeight - 52;
    });

    onActivated(() => {
      getCommitCountSelf();
    });

    return {
      query,
      isPhone,
      tableData,
      pageTotal,
      tableLoading,
      dateProgressRef,
      colorTabsRef,
      containerRef,
      onTabMethod,
      goWeekMethod,
      changeWeekMethod,
      cellContextMenuEvent,
      copyContentMethod,
      editTableDataMethod,
      deleteTableDataMethod,
      dateProgressHeight,
      getButtonList,
      createTableData,
      copyMethod,
      itemClickEvent,
      deleteAll,
      rowStyle,
      selectAllChangeEvent,
      selectChangeEvent,
      openWeekReportDialog,
      closeWeekReportDialog,
      clearWeekReport,
      weekReportDialogVisible,
      dialogShow,
      addWeekReport,
      addWeekReportAll,
      weekReportList,
      deleteWeekReportMethod,
      confirmExportWeekReport,
      weekReportDialogLoading,
      userInfo,
      isSelectCountShowAni,
      weekReportDateList,
      copySelection,
      reportFormDialogRef,
      refreshList,
      dateProgressYear,
      changeYearMethod,
      addWeekReportAllBtnLoading,
      handleSendTodayReport,
      sendTodayReportBtnLoading,
      reportCommitDialogRef,
      isShowSendReportBtn,
      getCommitCountSelf,
      viewSendedReport,
      nextWeekPlanList,
      addNextWeekPlanItem,
      deleteNextWeekPlanItem,
    };
  },
};
</script>

<style lang="less" scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
.year_box {
  position: absolute;
  top: -2px;
  left: -1px;
  z-index: 20;
  height: 35px;
  transform: rotate(-45deg);
  .year_icon {
    width: 100%;
    height: 100%;
    font-size: 13px;
    font-weight: 600;
    color: #666;
    background: url(../../assets/img/icons/fire.png) center center no-repeat;
    background-size: contain;
    display: flex;
    align-items: flex-end;
    justify-content: center;
    animation: year_ani 10s linear infinite;
  }
}

.week_report_btn {
  position: absolute;
  right: 20px;
  top: 10px;
  z-index: 10;

  .week_report_icon {
    cursor: pointer;
    width: 1.2em;
    height: 1.2em;
    color: #f56c6c;
  }

  .selected_report_count {
    position: absolute;
    top: -8px;
    left: 10px;
    padding: 2px 4px;
    border-radius: 4px;
    color: #fff;
    background-color: #f56c6c;
    font-size: 10px;
    transform: scale(0.7);
    transition: transform 0.3s ease-out;
    &.active {
      transform: scale(1.2);
    }
  }
}
.week_dialog_mask {
  // background-color: rgba(0,0,0,0.4);
  position: absolute;
  z-index: 100;
  top: 0;
  right: 0;
  width: 100%;
  height: 100%;
}
.week_dialog {
  position: absolute;
  top: 0;
  right: 0;
  width: 60%;
  height: 100%;
  background-color: #fff;
  transform-origin: 100% 0px 50px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  box-shadow: 1px -1px 10px rgba(0, 0, 0, 0.3);
  border-radius: 5px;
  overflow: hidden;
  transition: all 0.3s ease-out;
  transform: scale(0) rotate(0deg) translate(0px, 0px);
  opacity: 0;
  // transform: perspective(1000px) scale(0) rotate3d(1, 0, 0.2, 90deg)
  //   translate3d(103px, -29px, 106px);
  // transform: perspective(1000px) scale(0.1) rotate3d(1, 0, 0.2, 152deg) translate3d(705px, 431px, 867px);
  // transform: scale(0.1);
  &.show {
    transform: scale(1) rotate(0deg) translate(0px, 0px);
    opacity: 1;

    // transform: perspective(1000px) scale(1) rotate3d(0, 0, 0, 0deg)
    //   translate3d(0px, 0px, 10px);
  }

  .show_box {
    flex: 1;
    overflow: hidden auto;
  }

  .week_date_title {
    .week {
      font-size: 16px;
    }
    .date {
      font-size: 14px;
      color: #999;
    }
  }

  ul {
    list-style: none;
  }

  .list_item {
    position: relative;
    margin-bottom: 4px;
    border-radius: 4px;
    overflow: hidden;
    padding: 6px 10px;
    padding-right: 35px;
  }

  .list_item .bg_progress {
    background-color: #e6a23c;
    height: 100%;
  }

  .list_item .item_content {
    line-height: 22px;
    font-size: 16px;
    color: #333;
    width: 100%;
    word-break: break-all;
  }

  .list_item:hover {
    background-color: pink;
  }
  .list_item:hover .delete_btn {
    display: block;
  }
  .delete_btn {
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-44%);
    display: none;
    cursor: pointer;
    z-index: 10;
  }
}

.next_week_plan_box {
  .next_week_plan_item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    .icon {
      width: 30px;
      height: 30px;
      cursor: pointer;
      margin-left: 10px;
      &.add {
        color: #67c23a;
      }
      &.delete {
        color: #f56c6c;
      }
    }
  }
}

@keyframes year_ani {
  0% {
    transform: perspective(200px) rotate3d(0, 1, 0, 0deg);
  }
  80% {
    transform: perspective(200px) rotate3d(0, 1, 0, 0deg);
  }
  100% {
    transform: perspective(200px) rotate3d(0, 1, 0, 360deg);
  }
}

@keyframes scare_ani {
  0% {
    transform: scale(0);
    opacity: 0;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}
</style>

<style>
.xTable .vxe-body--row.row-checked {
  background-color: pink;
}
</style>
